package com.zhouxl.program.pipeline;

import com.zhouxl.aop.TimeCostAnnotation;
import com.zhouxl.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author zhouxl
 * @DATE 2021/7/9
 * @descriptoin
 */
@Component
public class RedisPipeline {

    @Autowired
    private RedisTemplate redisTemplate ;

    @TimeCostAnnotation
    public void execRedisPipelineCommand(){
        List list = redisTemplate.executePipelined((RedisCallback<String>) connection -> {
            //开启流水线
            connection.openPipeline();
            //批量执行任务
            for (int i = 0; i < Constants.NUM_MAX_WAN; i++) {
                Boolean aBoolean = connection.setNX(("key_" + i).getBytes(), ("value" + i).getBytes());
            }
            connection.closePipeline();
            return null;
        });
    }

    @TimeCostAnnotation
    public void execRedisSetCommand(){
        for (int i = 0; i < Constants.NUM_MAX_WAN; i++) {
            redisTemplate.opsForValue().set(("key_1_" + i), ("value" + i));
        }
    }

    /**
     * 执行批量任务中出现程序错误，会怎么样
     */
    public void execPipelineCommandException(){
        final int NUM = 10;
        List list = redisTemplate.executePipelined((RedisCallback<String>) connection -> {
            //开启流水线
            connection.openPipeline();
            //批量执行任务
            for (int i = 0; i < NUM; i++) {
                if( i == NUM - 1 ){
                    try {
                        throw new Exception("标识程序异常");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Boolean aBoolean = connection.setNX(("key_" + i).getBytes(), ("value" + i).getBytes());
            }
            connection.closePipeline();
            return null;
        });
        System.out.println(Arrays.toString(list.toArray()));
    }
}
